'use strict';
const md5 = require('md5');
const Service = require('egg').Service;

class SysRegisterService extends Service {


  async create(body) {
    const { app, ctx } = this;
    // 密码加盐加密
    body.password = md5(md5(body.pass) + app.config.password_salt);
    console.log(body);

    try {
      const exit = await ctx.model.Sys.User.findOne({
        where: { username: body.username },
      });
      if (exit) {
        return { success: false, msg: '账号已经存在！' };
      }

      return await ctx.model.transaction(async t => {

        // 创建用户信息
        const createUser = await ctx.model.Sys.User.create(body, { transaction: t });
        const role = await ctx.model.Sys.Role.findOne({
          where:{
            name:'用户'
          }
        })
        const userRoleArr = { role_id: role.dataValues.id, user_id: createUser.dataValues.id };
        // 创建用户角色
        await ctx.model.Sys.UserRole.create(userRoleArr);
        return true
      });
    } catch (error) {
      console.log(error);
      return { success: false };
    }
  }

}

module.exports = SysRegisterService;
